package hello; /** * 找出map中value最⼤的entry, 返回此entry, 并在map删除此entry * @param map * @return *//** * 从⽂件中读取待分割的⽂章素材. * @return * @throws IOException */

import java.io.*;
import java.util.HashMap;
import java.util.Map;


public class HelloWorld {
    public static void wordFrequency() throws IOException {
        Map map = new HashMap<>();
        String article = getString();
        String result = ToAnalysis.parse(article).toStringWithOutNature();
        String[] words = result.split(",");
        for (String word : words) {
            String str = word.trim(); // 过滤空⽩字符 if (str.equals("")) continue; // 过滤⼀些⾼频率的符号 else if(str.matches("[)|(|.|，|。|+|-|“|”|：|？|\\s]")) continue; // 此处过滤长度为1的str else if (str.length() < 2) continue;
            if (!map.containsKey(word)) {
                map.put(word, 1);
            } else {
                int n = map.get(word);
                map.put(word, ++n);
            }
        }
        Iterator > iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        List > list = new ArrayList<>();
        Map.Entry entry;
        while ((entry = getMax(map)) != null) {
            list.add(entry);
        }
        System.out.println(Arrays.toString(list.toArray()));
    }

    public static Map.Entry getMax(Map map) {
        if (map.size() == 0) {
            return null;
        }
        Map.Entry maxEntry = null;
        boolean flag = false;
        Iterator > iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            if (!flag) {
                maxEntry = entry;
                flag = true;
            }
            if (entry.getValue() > maxEntry.getValue()) {
                maxEntry = entry;
            }
        }
        map.remove(maxEntry.getKey());
        return maxEntry;
    }

    public static String getString() throws IOException {
        FileInputStream inputStream = new FileInputStream(new File("/home/as_/IdeaProjects/SpringMaven/article-txt"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder strBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            strBuilder.append(line);
        }
        reader.close();
        inputStream.close();
        return strBuilder.toString();
    }
}